import { defineComponent, h, onMounted, reactive, VNode } from 'vue';
import styles from '@/pages/MainMenu/common_page.module.scss';
import {
  createCommonDataTable,
  createCommonPagination,
  createCommonSearch
} from '@/pages/MainMenu/common_component_creator';
import { commonTableListReactive } from '@/pages/MainMenu/common_reactive';
import { getNamedBean, namedBean } from '@/util/reactive_obj_util';
import { DictionaryMapEnum, useDictionariesStore } from '@/config/pania_store/module/dictionary_store';
import { Apis } from '@/config/api_config/apis';
import {
  BaseFormItemConfigInterface,
  FormConfig
} from '@/util/vnode_create_util/dynamic_form_creator/dynamic_form_item_creator';
import { InputFormItemConfig } from '@/util/vnode_create_util/dynamic_form_creator/creator/input_creator';
import { SelectFormItemConfig } from '@/util/vnode_create_util/dynamic_form_creator/creator/select_creator';
import {
  createElTableColumns,
  createOperateActions,
  OperateButton,
  TableColumnConfig
} from '@/util/vnode_create_util/dynamic_table_column_creator';
import { DataStatus, WindUser } from '@/global';
import { startPageLoading, stopPageLoading } from '@/util/common_loading_util';
import { ApiCode } from '@/config/api_config/api_interface';
import { WindAccount } from '@/pages/MainMenu/User/WindAccount/WindAccountList';
import { ElTable, ElButton } from 'element-plus';
import { MessageService } from '@/config/component_config/custom_config/wind_component/MessageService/MessageService';
import { useToast } from 'vue-toastification';
import { ButtonFormItemConfig } from '@/util/vnode_create_util/dynamic_form_creator/creator/button_creator';

/**
 *风旅用户页面的bean管理enum
 */
export enum WindUserReactiveBeanEnum {
  windUserDialogReactive = 'windUserDialogReactive',
  windUserDataReactive = 'windUserDataReactive'
}
export interface UserSearch{
  userStatus: DataStatus | null;
  userNickName: string | null;
}

/**
 * 风旅用户页面
 */
export default defineComponent({
  name: 'WindUserList',
  setup () {
    const windListColumnDefine = getWindListColumnDefine(); // 风旅用户表格配置
    const windUserSearchDefine = getWindUserSearchDefine(); // 风旅列表查询条件配置
    const userReactive = namedBean(commonTableListReactive({ apiMethod: Apis.apiGetWindUserList, params: windUserSearchDefine.params }), WindUserReactiveBeanEnum.windUserDataReactive); // 列表响应对象
    namedBean(windUserDialogReactive(), WindUserReactiveBeanEnum.windUserDialogReactive);

    onMounted(() => {
      useDictionariesStore().gainDictionary(DictionaryMapEnum.dataStatus);
    });
    return () => <div class={`${styles.page_container}`}>
      {/* 风旅用户列表查询条件 */}
      { createCommonSearch(windUserSearchDefine.searchFormConfig)}
      {/* 风旅用户列表 */}
      { createCommonDataTable({ data: userReactive.dataList, loading: userReactive.tableLoading, defineColumns: windListColumnDefine })}
      {/* 底部的分页 */}
      { createCommonPagination({ page: userReactive.page, changePageFunction: userReactive.onLoad })}
    </div>;
  }
});

/**
 * 风旅用户表查询条件定义
 */
const getWindUserSearchDefine = () => {
  const dictionariesStore = useDictionariesStore();
  const params = reactive<UserSearch>({ userStatus: null, userNickName: null }); // 查询参数
  const searchColumnDefine: BaseFormItemConfigInterface<UserSearch>[] = [
    new InputFormItemConfig({ label: '昵称', colSpan: 6 }),
    new SelectFormItemConfig({ label: '用户状态', prop: 'userStatus', options: () => dictionariesStore.getDictionary(DictionaryMapEnum.dataStatus), colSpan: 6 }),
    {
      prop: 'userStatus',
      createMethod (config, formData): VNode {
        return <div></div>;
      }
    }
  ];
  const searchFormConfig: FormConfig<UserSearch> = {
    bindData: params,
    labelWidth: '80px',
    labelPosition: 'right',
    itemsConfig: searchColumnDefine
  };
  return { params, searchFormConfig };
};

/**
 * 风旅用户表的列表结构定义
 */
const getWindListColumnDefine = () => {
  // 操作按钮定义
  const operateButtons: OperateButton<WindUser>[] = [
    {
      title: '账户',
      action: async (scope) => {
        await getNamedBean<ReturnType<typeof windUserDialogReactive>>(WindUserReactiveBeanEnum.windUserDialogReactive)?.openBoundAccountsDialog(scope.row);
      },
      isShow: () => true
    },
    {
      title: '编辑',
      action: () => {

      },
      isShow: (scope) => scope.row.userStatus === DataStatus.Normal
    },
    {
      title: (scope) => scope.row.userStatus === DataStatus.Deleted ? '还原' : '激活',
      action: async (scope) => {
        await getNamedBean<ReturnType<typeof windUserDialogReactive>>(WindUserReactiveBeanEnum.windUserDialogReactive)?.openActiveWindUserDialog(scope.row);
      },
      isShow: (scope) => scope.row.userStatus === DataStatus.Inactivated || scope.row.userStatus === DataStatus.Deleted
    },
    {
      title: '删除',
      action: async (scope) => {
        await getNamedBean<ReturnType<typeof windUserDialogReactive>>(WindUserReactiveBeanEnum.windUserDialogReactive)?.openDeleteWindUserDialog(scope.row); ;
      },
      isShow: () => true
    }
  ];

  // 三年审核计划的列表组成配置参数
  const windUserColumn: TableColumnConfig<WindUser>[] = [
    { label: '昵称', width: '160px', dom: scope => <span>{scope.row.userNickName}</span> },
    { label: '邮箱', width: '220px', dom: scope => <span>{scope.row.userEmail}</span> },
    { label: '性别', width: '60px', dom: scope => <span>{scope.row.userSexText}</span> },
    { label: '等级', width: '120px', dom: scope => <span>{scope.row.userLevel}</span> },
    { label: '真实姓名', width: '120px', dom: scope => <span>{scope.row.userRealName}</span> },
    { label: '手机号', width: '120px', dom: scope => <span>{scope.row.userMobile}</span> },
    { label: '用户状态', dom: scope => <span>{scope.row.userStatusText}</span> },
    { label: '操作', width: '160px', fixed: 'right', dom: scope => <div>{createOperateActions(operateButtons, scope)}</div> }
  ];
  return windUserColumn;
};

function windUserDialogReactive () {
  /**
   * 获取wind用户绑定的账号
   * @param windUser 要查询的用户
   */
  const openBoundAccountsDialog = async (windUser: WindUser) => {
    // 从后端请求数据
    startPageLoading();
    const res = await Apis.apiGetBoundUser(windUser.userId).finally(stopPageLoading);
    // 如果能查询到绑定的用户，就打开对话框，否则直接返回
    if (res.apiCode === ApiCode.Success && res.result.length !== 0) {
      const windAccountColumn: TableColumnConfig<WindAccount>[] = [
        { label: '账号名称', width: '140px', dom: scope => <div>{scope.row.accountName}</div> },
        { label: '账号类别', width: '100px', dom: scope => <div>{scope.row.accountTypeText}</div> },
        { label: '创建人', width: '180px', dom: scope => <div>{scope.row.createNickName}</div> },
        { label: '最近更新人', dom: scope => <div>{scope.row.updateNickName}</div> }
      ];
      const tableSlot = (): VNode | string => {
        return <div>
          <ElTable data={res.result}>
            {createElTableColumns(windAccountColumn)}
          </ElTable>
        </div>;
      };
      MessageService.windDialog({
        title: `账户:${windUser.userNickName}`,
        defaultSlot: tableSlot,
        width: '60%'
      });
    } else {
      useToast().error('未查询到绑定用户');
    }
  };

  /**
   * 删除wind用户
   * @param windUser 要删除的wind用户
   */
  const openDeleteWindUserDialog = async (windUser: WindUser) => {
    await MessageService.windConfirm('确定要删除该用户!', '删除', async (instance, done) => {
      instance.confirmButtonLoading = true;
      const res = await Apis.apiDeleteWindUser(windUser.userId).finally(() => {
        instance.confirmButtonLoading = false;
      });
      if (res.apiCode === ApiCode.Success) {
        useToast().success('已成功删除该用户!');
        getNamedBean<ReturnType<typeof commonTableListReactive>>(WindUserReactiveBeanEnum.windUserDataReactive)?.onLoad();
        done();
      }
    });
  };

  /**
   * 激活wind用户
   * @param windUser 要激活的wind用户
   */
  const openActiveWindUserDialog = async (windUser: WindUser) => {
    const activeTitle = windUser.userStatus === DataStatus.Inactivated ? '激活' : '还原';
    await MessageService.windConfirm(`确定要${activeTitle}该账户?`, activeTitle, async (instance, done) => {
      instance.confirmButtonLoading = true;
      const res = await Apis.apiActiveWindUser(windUser.userId).finally(() => {
        instance.confirmButtonLoading = false;
      });
      if (res.apiCode === ApiCode.Success) {
        useToast().success(`已成功${activeTitle}该用户!`);
        getNamedBean<ReturnType<typeof commonTableListReactive>>(WindUserReactiveBeanEnum.windUserDataReactive)?.onLoad();
        done();
      }
    });
  };

  return { openBoundAccountsDialog, openDeleteWindUserDialog, openActiveWindUserDialog };
}
